package com.kqb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.kqb.common.domain.AjaxResult;
import com.kqb.common.domain.pojo.User;
import com.kqb.common.utils.StringUtils;
import com.kqb.mapper.PublicUserMapper;
import com.kqb.service.IPublicUserService;
import com.kqb.token.TokenTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Map;

/**
 * @author 杉果树皮
 * @date 2025/2/26 8:03
 * @description:
 */
@Service
public class PublicUserServiceImpl implements IPublicUserService {
    @Autowired
    private PublicUserMapper publicUserMapper;
    @Autowired
    private TokenTemplate tokenTemplate;

    @Override
    public AjaxResult login(User user) {

        User user1 = publicUserMapper.selectByAccount(user);
        //判断账号是否存在
        if (StringUtils.isNull(user1))
            return AjaxResult.error(201, "账号不存在");
        //判断密码是否正确
        if (!user1.getPassword().equals(DigestUtils.md5DigestAsHex(user.getPassword().getBytes())))
            return AjaxResult.error(202, "密码错误");

        if (user1.getStatus() == 2)
            return AjaxResult.error(203, "该账号已封禁，请联系管理员");
        //账号密码都正确
        Map<String, Object> map = BeanUtil.beanToMap(user1);
        String[] roles = new String[1];
        String userInfo = null;
        Integer saleId = null;
        switch (user1.getType()) {
            case 1:
                userInfo = (String) publicUserMapper.getEmployee(user1.getId()).get("real_name");
                if (user1.getAccount().startsWith("admin")) {
                    roles[0] = "admin";
                } else {
                    roles[0] = "sale";
                }
                break;
            case 2:
                userInfo = (String) publicUserMapper.getCustomer(user1.getId()).get("contacts");
                saleId = (Integer) publicUserMapper.getCustomer(user1.getId()).get("sale_id");
                roles[0] = "customer";
                break;
            case 3:
                roles[0] = "supplier";
                break;
            case 4:
                roles[0] = "forwarder";
                break;
        }
        map.put("userInfo", userInfo);
        map.put("saleId", saleId);
        map.put("roles", roles);
        map.put("id", map.get("id"));
        map.remove("type");
        map.remove("status");
        map.remove("password");
        String username = user1.getAccount();
        map.put("username", username);
        String token = tokenTemplate.generateToken(map);
        map.put("accessToken", token);
        return AjaxResult.success("登录成功", map);
    }
}
